<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="800"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form label-width="120px" :model="form" :rules="rules" ref="formRef">
      <el-row>
        <el-col :span="22">
          <el-form-item :label="t('business.price.name')" prop="name">
            <el-input v-model="form.name" :placeholder="t('business.price.validator.name')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item :label="t('business.price.type')" prop="type">
            <el-radio-group v-model="form.type" :disabled="form.id != undefined">
              <el-radio :label="item.value" :value="item.value" :key="index" v-for="(item, index) in PriceTypeEnum">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="22">
          <el-form-item :label="t('crud.table.column.note')" prop="note">
            <el-input type="textarea" v-model="form.note" :placeholder="t('crud.table.column.note')" :autosize="{ minRows: 2, maxRows: 10 }" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.type == PriceTypeEnum.Standard.value">
        <el-col :span="24">
          <el-divider content-position="left">{{t('business.price.action.standard')}}</el-divider>
          <div class="el-form-item" style="display: block; margin: 0; padding: 0">
            <el-row :gutter="0">
              <el-col :span="5">
                <div class="pr-5" style="text-align:right; line-height:32px;"><span style="color:red; margin-right: 3px; font-size: 16px;">*</span>{{t('business.price.elecFee')}}</div></el-col>
              <el-col :span="6">
                <div><el-input-number style="width: 180px" :min="0" :max="10" :step="0.01" :precision="4" v-model="form.properties.fee[0].elecFee" @change="validateProperties" :placeholder="t('business.price.placeholder.elecFee')" /></div>
              </el-col>
              <el-col :span="5"><div class="pr-5" style="text-align:right; line-height:32px;"><span style="color:red; margin-right: 3px; font-size: 16px;">*</span>{{t('business.price.serviceFee')}}</div></el-col>
              <el-col :span="6">
                <div><el-input-number style="width: 180px" :min="0" :max="10" :step="0.01" :precision="4"  v-model="form.properties.fee[0].serviceFee" @change="validateProperties" :placeholder="t('business.price.placeholder.serviceFee')" /></div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :offset="5">
          <div style="color: #f56c6c; font-size:12px" class="m-1">{{errors.standard}}</div>
        </el-col>
      </el-row>

      <div v-if="form.type == PriceTypeEnum.Tou.value">
        <el-row :gutter="0">
          <el-col :span="22">
            <el-divider content-position="left">{{t('business.price.action.tou')}}</el-divider>
            <el-row :gutter="0" :key="index" v-for="(fee, index) in form.properties.fee">
              <el-col :span="12">
                <el-row :gutter="0">
                  <el-form-item required :label="fee.name + t('business.price.elecFee')">
                    <el-input-number style="width: 180px" :min="0" :max="10" :step="0.01" :precision="4"  v-model="fee.elecFee" @change="validateProperties" :placeholder="fee.name + t('business.price.elecFee')" />
                  </el-form-item>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-row :gutter="0">
                  <el-form-item required :label="fee.name + t('business.price.serviceFee')">
                    <el-input-number style="width: 180px" :min="0" :max="10" :step="0.01" :precision="4"  v-model="fee.serviceFee" @change="validateProperties" :placeholder="fee.name + t('business.price.serviceFee')" />
                  </el-form-item>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :offset="4">
            <div style="color: #f56c6c; font-size:12px" class="m-1">{{errors.topFee}}</div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-divider content-position="left">
              {{t('business.price.action.interval')}}
              <el-button
                size="small"
                v-for="(fee, index) in priceFeeData"
                :key="index"
                :style="{
                  color: currentFee == index ? 'white' : 'black',
                  borderWidth: 1,
                  borderStyle: 'solid',
                  borderColor: fee.color,
                  backgroundColor: currentFee == index ? fee.color : '',
              }"
                @click="handleSettingTou(index)"
                >{{fee.name}}</el-button
              >
            </el-divider>
            <el-row :gutter="0">
              <el-col :span="4"></el-col>
              <el-col :span="20">
                <el-row>
                  <el-col :span="4" class="p-1" v-for="(interval, index) in form.properties.period" :key="index">
                    <el-button
                      @click="handleClickInterval(index)"
                      :style="{
                      width: '100%',
                      color: interval.index !== undefined ? 'white' : 'black',
                      backgroundColor: interval.index !== undefined ? priceFeeData[interval.index].color : ''
                    }"
                      >{{ interval.label }}</el-button
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :offset="4">
            <div style="color: #f56c6c; font-size:12px" class="m-1">{{errors.topInterval}}</div>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClose" :loading="state.loading">{{ t('crud.cancelText') }}</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="state.loading">{{t('crud.confirmText')}}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import { PriceForm} from '@/api/business/priceCharge/types'
import {priceFeeData, pricePeriodData} from '@/api/business/priceCharge/data'
import {priceSave } from '@/api/business/priceCharge'
import {FormInstance, FormRules} from 'element-plus'
import {ComponentInternalInstance} from 'vue'

import {useI18n} from 'vue-i18n'
const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { PriceTypeEnum } = toRefs<any>(proxy?.useEnum('price_type_enum'))
const emits = defineEmits(['success'])

const currentFee = ref<number|undefined>(undefined)
const formRef = ref<FormInstance>()

const errors = ref<any>({
  standard: '',
  topFee: '',
  topInterval: ''
})

const state = reactive({
  update: false,
  visible: false,
  loading: false,
  title: '',
})

const form = ref<PriceForm>({
  id: undefined,
  name: '',
  type: '',
  status: '',
  note: '',
  properties: {
    fee: [],
    period: [],
  }
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: t('business.price.validator.name'), trigger: 'blur' }],
  type: [{ required: true, message: t('business.price.validator.type'), trigger: 'blur' }],
})

watch(
  () => form.value.type, (newV) => {
    if(newV) {
      handlePriceTypeChange()
    }
  },
  {
    immediate: true,
    // deep: true,
  }
)

const openDialog = (row?: any) => {
  state.visible = true
  if(row) {
    state.update = true
    state.title = t('business.price.action.edit')
    form.value = Object.assign({}, row)
  } else {
    state.update = false
    state.title = t('business.price.action.add')
    form.value = {
      id: undefined,
      name: '',
      type: 'Standard',
      note: '',
      properties: {
        fee: [{
          name: t('business.price.standard'),
          elecFee: undefined,
          serviceFee: undefined
        }],
        period: pricePeriodData,
      }
    }
  }
}

const handleClose = () => {
  state.visible = false
}


const handleSettingTou = (inx) => {
  currentFee.value = inx
}

const handlePriceTypeChange = () => {
  if(!state.update) {
    if(form.value.type == 'Standard') {
      form.value.properties = {
        fee: [{
          name: t('business.price.standard'),
          elecFee: undefined,
          serviceFee: undefined
        }],
        period: pricePeriodData,
      }
    } else {
      form.value.properties.fee = priceFeeData
      form.value.properties.period = pricePeriodData
    }
  }
}

const handleClickInterval = (index) => {
  if(currentFee.value === undefined) {
    ElMessage.error(t('business.price.validator.type'))
    return
  }
  form.value.properties.period[index].index = form.value.properties.period[index].index !== undefined ? undefined : currentFee.value
}

const validateProperties = () => {
  errors.value = {
    standard: '',
    topFee: '',
    topInterval: ''
  }
  if(form.value.type === 'Standard') {
    if(!form.value.properties.fee || form.value.properties.fee.length == 0) {
      ElMessage.error(t('operate.tooltip.paramsError'))
      return true
    }
    let fee = form.value.properties.fee[0]

    let formatted = format(Number(fee.elecFee))
    if(formatted == undefined ||isNaN(formatted)) {
      form.value.properties.fee[0].elecFee = undefined
    } else {
      form.value.properties.fee[0].elecFee = formatted
    }

    if(!fee.elecFee) {
      errors.value.standard = t('business.price.validator.standardElecFee')
      return true
    }

    formatted = format(Number(fee.serviceFee))
    if(formatted == undefined ||isNaN(formatted)) {
      form.value.properties.fee[0].serviceFee = undefined
    } else {
      form.value.properties.fee[0].serviceFee = formatted
    }
    if(!fee.serviceFee) {
      errors.value.standard = t('business.price.validator.standardServiceFee')
      return true
    }
  } else {
    if(!form.value.properties.fee || form.value.properties.fee.length !== 4) {
      ElMessage.error(t('operate.tooltip.paramsError'))
      return true
    }
    let hasError = false
    form.value.properties.fee.forEach((fee, index)=>{
      let formatted = format(Number(fee.elecFee))
      if(formatted== undefined || isNaN(formatted)) {
        form.value.properties.fee[index].elecFee = undefined
      } else {
        form.value.properties.fee[index].elecFee = formatted
      }

      if(!fee.elecFee) {
        hasError = true
        errors.value.topFee = t('business.price.validator.touElecFee')

        console.log(fee.name)
        return
      }

      let formatted2 = format(Number(fee.serviceFee))
      if(formatted2 == undefined ||isNaN(formatted2)) {
        form.value.properties.fee[index].serviceFee = undefined
      } else {
        form.value.properties.fee[index].serviceFee = formatted2
      }

      if(!fee.serviceFee) {
        hasError = true
        errors.value.topFee = t('business.price.validator.touServiceFee', {name: fee.name})
        return
      }
    })
    if(hasError) {
      return true
    }

    hasError = false
    if(!form.value.properties.period || form.value.properties.period.length !== 48) {
      hasError = true
      ElMessage.error(t('operate.tooltip.paramsError'))
      return
    }

    form.value.properties.period.forEach((interval)=>{
      if(interval.index === undefined) {
        hasError = true
        errors.value.topInterval = t('business.price.validator.topInterval')
        return
      }
    })

    if(hasError) {
      return true
    }

    return false
  }
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let hasError = validateProperties()

      console.log(hasError)
      if(hasError) {
        return
      }

      state.loading = true
      let data = Object.assign({}, form.value)

      await priceSave(data).finally(() => (state.loading = false))
      ElMessage.success(t('operate.tooltip.success'))
      handleClose()
      emits('success', data)
    }
  })
}


const format = (num:number|undefined) =>{
  let n = 4
  if(num == undefined) {
    return num
  }
  let formattedNum = num.toFixed(n)

  if(formattedNum) {
    return Number(formattedNum)
  }
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})
</script>
